import React from 'react'
// ===================================================================== antd
import { DndProvider, useDrag, useDrop } from 'react-dnd'
import { HTML5Backend } from 'react-dnd-html5-backend'
import update from 'immutability-helper'
import { ArrowUpOutlined, ArrowDownOutlined  } from '@ant-design/icons'
// ===================================================================== declare
const { $fn, $Lazy } = window
// ===================================================================== Temp
const Modal 	= $Lazy.state(()=>import('@antd/modal'))
const Table 	= $Lazy.state(()=>import('@antd/table'))
const Button 	= $Lazy.state(()=>import('@antd/button'))
const Input 	= $Lazy.load(()=>import('@antd/form/input'))
const Switch 	= $Lazy.load(()=>import('@antd/form/switch'))
// 添加相关操作说明 20210928 耿琰
const Ask 		= $Lazy.load(()=>import('#tp/ask'))
// ===================================================================== 自定义拖拽
const type = 'DragableBodyRow'
	
const DragableBodyRow = ({ index, moveRow, className, style, ...restProps }) => {
	const ref = React.useRef();
	const [{ isOver, dropClassName }, drop] = useDrop(  () => ({
		accept: type,
		collect: monitor => {
			const { index: dragIndex } = monitor.getItem() || {}
			if (dragIndex === index) { return {}  }
			return {
				isOver: monitor.isOver(),
				dropClassName: dragIndex < index ? ' drop-over-downward' : ' drop-over-upward'
			};
		},
		drop: item =>  moveRow(item.index, index),
	}), [index])
	
	const [, drag] = useDrag(() => ({
		type,
		item: { index },
		collect: monitor => ({isDragging: monitor.isDragging()})
	}),[index])
	
	drop(drag(ref))
	
	return (
		<tr
			ref			= { ref }
			className	= {`${className?className:''} ${isOver ? dropClassName : ''}`}
			style		= {{ cursor: 'move', ...style }}
			{...restProps}
		/>
	)
}
	
// ===================================================================== component
const Index = ({ onSelect, sort, onRefresh }, ref)=>{
	const [ data, setData ] = React.useState([])
	const [ keys, setKeys ] = React.useState([])
	const [ key, seKey ] = React.useState(0)
	const modalRef = React.useRef()
	const nameRef = React.useRef()
	// 复位
	const reset = React.useCallback( data =>{
		const len = data.length
		data.forEach((v,i)=>{
			v.index = i + 1
			v.save = i + 1
			v.last = i + 1 === len
			v.upClick = null
			v.downClick = null
		})
	},[])
	
	React.useImperativeHandle( ref, () => ({
		open : (cols, name) => {
			if(!modalRef.current.refs.ref){ return }
			modalRef.current.refs.ref.open()
			const len = cols.length
			const saveName = name ? name : $fn.getPath()
			nameRef.current = saveName
			let _data = $fn.longSave([ saveName ])
			
			if(!$fn.hasArray(_data)){
				
				cols.forEach((v,i) => {
					v.show = true
					v.index = i + 1
					v.save = i + 1
					v.last = i + 1 === len
				})
				_data = cols
			}else{
				// data.forEach((v,i) => {
				// 	v.index = i + 1
				// 	v.save = i + 1
				// })
			}
			
			const _keys = _data.map(v=>{
				return v.show ? v['dataIndex'] : null
			})
			setData(_data)
			setKeys(_keys)
			seKey(key => key + 1)
		}
	}))
	
	let cols = [
		// 添加相关操作说明 20210928 耿琰
		{ title:() => <div className='fxm'>列名<Ask name='tableColTip' /></div>, dataIndex:'title' },
		{ title:'列宽', dataIndex:'width', render: (text,rows)=>(
			<Input value={text} clear={false} style={{padding:'2px 5px'}} onChange={value=> {
				rows.width = +value
			}} />
		) },
		{ title:'定位排序', dataIndex:'index', align:'center', render: (text, rows) => (
			<Input key={rows['index']+1} value={text} onDrag={e=>e.stopPropagation()} clear={false} style={{padding:'2px 5px'}} onChange={value => {
				rows['index'] = value
				// setTimeout(()=> setData( data => [...data] ))
			}} onBlur = { value => {
				value = +value
				const save = +rows['save']
				if( value === +rows['save']){
					
				}else{
					setData( data => {
						if(value > 0 && value <= data.length){
							
							if(value < save){
								data.splice(value-1, 0, rows)
								data.splice(save, 1)
							}else{
								data.splice(value, 0, rows)
								data.splice(save-1, 1)
							}
						
							reset(data)
						}else{
							rows['index'] = save
							$fn.toast(`排范围为[1 ~ ${data.length}]`)
						}
						return [...data]
					} )
				}
			}} />
		) },
		{ title:'移动排序', align:'center', render: (text, rows)=>(
			<>
				<Button style={{minWidth:40}} disabled={+rows.save === 1} ghost={!rows.upClick} danger icon={<ArrowUpOutlined/>} onClick={()=>{
					const index = +rows['index'] - 2
					const save =  +rows['save']
					rows['index'] = index
					
					setData( data => {
						data.splice(index, 0, rows)
						data.splice(save, 1)
						reset(data)
						rows.upClick = true
						return [...data]
					} )
				}}/>
				<Button style={{minWidth:40}} disabled={rows.last} ghost={!rows.downClick} danger className='ml10' icon={<ArrowDownOutlined/>} onClick={()=>{
					const index = +rows['index'] + 1
					const save =  +rows['save'] - 1
					rows['index'] = index
					
					setData( data => {
						data.splice(index, 0, rows)
						data.splice(save, 1)
						reset(data)
						rows.downClick = true
						return [...data]
					} )
				}}/>
			</>
		) },
		// 添加相关操作说明 20210928 耿琰
		sort ? { title:() => <div className='fxm'>是否排序搜索<Ask name='tableSortTip' /></div>, dataIndex:'sorter', align:'center', render: (text, rows) => (
			<Switch value={rows.sorter} isBool onChange={value=> {
				rows.sorter = value
			}} />
		) } : {},
	]
	
	cols = cols.filter(v => $fn.hasObject(v))
	
	const moveRow = React.useCallback((dragIndex, hoverIndex) => {
		setData(update(data, {$splice: [ [dragIndex, 1],[hoverIndex, 0, data[dragIndex]]] }))
		// 复位排序
		setTimeout(()=> setData( data => { reset(data); return [...data]} ), 100)
	},[data, reset])
	
	return (
		<Modal
			ref		= { modalRef }
			title 	= {'设置表头' + key }
			width	= '50%' 
			height	= '90%'
			enter
			isFullScroll
			onOk	= {()=>{
				data.forEach(v=>{
					v.show = false
					keys.forEach(p=>{
						if(v.dataIndex === p){
							v.show = true
						}
					})
				})
				$fn.longSave([ nameRef.current ], data)
				modalRef.current.refs.ref.close()
				onRefresh?.()
			}}
		>
			<DndProvider backend={HTML5Backend}>
				<div className='abs_full fv pt10' id='components-table-demo-drag-sorting' key={key}>
					<Table
						data			= { data }
						cols			= { cols }
						type			= 'checkbox'
						selectedKeys	= {keys}
						idStr 			= 'dataIndex'
						className		= 'table-sm'
						components		= {{ body: { row: DragableBodyRow } }}
						onMyRow			= {(record, index) => ({
							index,
							moveRow
						})}
						onSelect		= { keys => setKeys(keys) }
					/>
				</div>
			</DndProvider>
		</Modal>
	)
}
export default Index